//
//  WLTabBarItem.m
//  WLTabBar
//
//  Created by tanxl on 2019/12/29.
//  Copyright © 2019 tanxl. All rights reserved.
//

#import "WLTabBarItem.h"
#import "Masonry.h"

NSString *const kGTNotificationTabBarItemChanged = @"kGTNotificationTabBarItemChanged";

@interface WLTabBarItem ()

/** 图标 */
@property (nonatomic, strong) UIImageView *imageView;
/** 文字 */
@property (nonatomic, strong) UILabel *titleLabel;
/** 按钮 */
@property (nonatomic, strong) UIButton *button;

@property (nonatomic, strong) UILabel *tabBarBadge;

@end

@implementation WLTabBarItem

- (void)dealloc {
    /// 需要同步什么信息就监听并实现对应的逻辑
    [self.tabBarItem removeObserver:self forKeyPath:@"badgeValue"];
    [self.tabBarItem removeObserver:self forKeyPath:@"title"];
    [self.tabBarItem removeObserver:self forKeyPath:@"image"];
    [self.tabBarItem removeObserver:self forKeyPath:@"selectedImage"];
}

- (instancetype)initWithType:(WLTabBarItemType)tabBarItemType{
    self = [super init];
    if (self) {
        switch (tabBarItemType) {
            case WLTabBarItemTypeNormal:
                [self initNormal];
                break;
            case WLTabBarItemTypeOnlyImage:
                [self initImage];
                break;
            case WLTabBarItemTypeButton:
                [self initButton];
                break;
            default:
                break;
        }
    }
    return self;
}
-(void)initNormal{
    [self addSubview:self.titleLabel];
    [self addSubview:self.imageView];

    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self);
        make.height.mas_offset(12);
        make.bottom.mas_equalTo(self).mas_offset(-4);
    }];
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self).mas_offset(4);
        make.bottom.mas_equalTo(self.titleLabel.mas_top).mas_offset(-1);
        make.centerX.mas_equalTo(self);
        make.width.mas_equalTo(self.imageView.mas_height);
    }];
    
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tabBarItemClick:)];
    [self addGestureRecognizer:tapGR];
}

-(void)initImage{
    [self addSubview:self.imageView];
    [self addSubview:self.tabBarBadge];
    
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self);
        make.top.mas_equalTo(self).mas_offset(2);
        make.bottom.mas_equalTo(self).mas_offset(-2);
        make.width.mas_equalTo(self.imageView.mas_height);
    }];
    [self.tabBarBadge mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.imageView).mas_offset(-5);
        make.top.mas_equalTo(self.imageView).mas_offset(5);
        make.height.mas_offset(15);
        make.width.mas_greaterThanOrEqualTo(15);
    }];
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tabBarItemClick:)];
    [self addGestureRecognizer:tapGR];
}

-(void)initButton{
    [self addSubview:self.button];
    [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self);
        make.height.mas_offset(23);
        make.width.mas_offset(23);
    }];
}

- (void)tabBarItemClick:(UITapGestureRecognizer *)tap {
    [self buttonItemClick:nil];
}
-(void)buttonItemClick:(UIButton *)sender{
    if ([self.delegate respondsToSelector:@selector(onClickTabBarItem:)]){
        [self.delegate onClickTabBarItem:self];
    }
}


#pragma mark -
- (void)setSelected:(BOOL)selected {
    _selected = selected;
    [self updateViewContent];
}

- (void)setBadgeTitleFont:(UIFont *)badgeTitleFont {
    _badgeTitleFont = badgeTitleFont;
}

- (void)setItemTitleFont:(UIFont *)itemTitleFont{
    _itemTitleFont = itemTitleFont;
    if (itemTitleFont) {
        self.titleLabel.font = itemTitleFont;
    }
}

- (void)setItemTitleColor:(UIColor *)itemTitleColor{
    _itemTitleColor = itemTitleColor;
}

- (void)setSelectedItemTitleColor:(UIColor *)selectedItemTitleColor{
    _selectedItemTitleColor = selectedItemTitleColor;
}

#pragma mark -

- (void)setTabBarItem:(UITabBarItem *)tabBarItem {
    _tabBarItem = tabBarItem;
    [tabBarItem addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionNew context:nil];
    [tabBarItem addObserver:self forKeyPath:@"selectedImage" options:NSKeyValueObservingOptionNew context:nil];
    [tabBarItem addObserver:self forKeyPath:@"badgeValue" options:NSKeyValueObservingOptionNew context:nil];
    [tabBarItem addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    [self observeValueForKeyPath:nil ofObject:nil change:nil context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    [[NSNotificationCenter defaultCenter] postNotificationName:kGTNotificationTabBarItemChanged object:nil];
    [self updateViewContent];
}

- (void)updateViewContent {
    // 文字
    if ([self.subviews containsObject:self.titleLabel]){
        NSDictionary *textAttributes = self.selected ? [[UITabBarItem appearance] titleTextAttributesForState:(UIControlStateSelected)] : [[UITabBarItem appearance] titleTextAttributesForState:(UIControlStateNormal)];
        if (textAttributes.count) {
            NSString *name = self.tabBarItem.title;
            self.titleLabel.attributedText = [[NSAttributedString alloc] initWithString:name attributes:textAttributes];
        }else{
            self.titleLabel.text = self.tabBarItem.title;
            self.titleLabel.textColor = self.isSelected ? self.selectedItemTitleColor : self.itemTitleColor;
        }
    }
    //图片
    if ([self.subviews containsObject:self.imageView]){
        UIImage *image = self.selected ? self.tabBarItem.selectedImage : self.tabBarItem.image;
        if (image == nil) {
            image = self.selected ? [self.tabBarItem valueForKey:@"_selectedTemplateImage"] : [self.tabBarItem valueForKey:@"_templateImage"];
        }
        self.imageView.image = image;
    }
    //未读数量
    if ([self.subviews containsObject:self.tabBarBadge]){
        NSInteger count = [self.tabBarItem.badgeValue integerValue];
        self.tabBarBadge.hidden = !count;
        self.tabBarBadge.text = [NSString stringWithFormat:@"%ld",(count>99)?99:count];
    }
    //按钮
    if ([self.subviews containsObject:self.button]){
        UIImage *image = self.selected ? self.tabBarItem.selectedImage : self.tabBarItem.image;
        if (image == nil) {
            image = self.selected ? [self.tabBarItem valueForKey:@"_selectedTemplateImage"] : [self.tabBarItem valueForKey:@"_templateImage"];
        }
        [self.button setBackgroundImage:image forState:UIControlStateNormal];
    }
}


#pragma mark -- 懒加载
-(UILabel *)titleLabel{
    if (!_titleLabel){
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont systemFontOfSize:14];
    }
    return _titleLabel;
}
-(UIImageView *)imageView{
    if (!_imageView){
        _imageView = [[UIImageView alloc] init];
        _imageView.contentMode = UIViewContentModeScaleAspectFit;
    }
    return _imageView;
}
-(UIButton *)button{
    if (!_button){
        _button = [[UIButton alloc]init];
        [_button addTarget:self action:@selector(buttonItemClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _button;
}
-(UILabel *)tabBarBadge{
    if (!_tabBarBadge){
        _tabBarBadge = [[UILabel alloc]init];
        _tabBarBadge.textColor = UIColor.whiteColor;
        _tabBarBadge.font = [UIFont systemFontOfSize:9];
        _tabBarBadge.backgroundColor = UIColor.redColor;
        _tabBarBadge.textAlignment = NSTextAlignmentCenter;
        _tabBarBadge.layer.cornerRadius = 15/2.f;
        _tabBarBadge.clipsToBounds = YES;
    }
    return _tabBarBadge;
}
@end

